﻿#include "pch.h"
#include "log_write.h"
#include <atlstr.h>
#include <atltime.h>
#include <io.h>
#include <string.h>
#include <direct.h>

CLogWrite::CLogWrite(const char *file_name)
{
	strcpy(g_log_file_name_prefix, file_name);
}

inline HMODULE __stdcall ModuleFromAddress(PVOID pv)
{
	MEMORY_BASIC_INFORMATION mbi;
	if (::VirtualQuery(pv, &mbi, sizeof(mbi)) != 0)
	{
		return (HMODULE)mbi.AllocationBase;
	}
	else
	{
		return NULL;
	}
}

inline HMODULE WINAPI GetCurrentModule()
{
	HMODULE hModule = ModuleFromAddress(((void *)&GetCurrentModule));

	return hModule;
}

//写日志文件
void CLogWrite::WriteLogFile(const char *data)
{
	time_t now;
	struct tm t;
	char current_time[20] = {0};
	char write_data[1024] = {0};
	SYSTEMTIME st;

	time(&now);			   // 获取系统日期和时间
	localtime_s(&t, &now); // 获取当地日期和时间

	GetLocalTime(&st);

	sprintf(current_time, "_%04d-%02d-%02d", st.wYear, st.wMonth, st.wDay);

	CString path_str = g_log_file_path;
	path_str += "\\";
	path_str += g_log_file_name_prefix;

	// 判断是否存在指定的路径(存储日志路径)
	int ret = _access(g_log_file_path, 0);
	if (-1 == ret)
	{
		int ret = _mkdir(g_log_file_path);
		if (0 != ret)
		{
			return;
		}
	}

	path_str += current_time;
	path_str += ".log";

	HANDLE hFile = CreateFile(path_str.GetBuffer(path_str.GetLength()),
							  (GENERIC_WRITE | GENERIC_READ),
							  (FILE_SHARE_READ | FILE_SHARE_WRITE),
							  NULL,
							  OPEN_ALWAYS,
							  FILE_ATTRIBUTE_ARCHIVE,
							  NULL);
	path_str.ReleaseBuffer();

	if (hFile == INVALID_HANDLE_VALUE)
	{
		return;
	}

	int nFileLen = GetFileSize(hFile, NULL);
	SetFilePointer(hFile, nFileLen, NULL, FILE_BEGIN);

	sprintf_s(write_data, "[%04d-%02d-%02d %02d:%02d:%02d:%03d]\t%s\r\n",
			  st.wYear, st.wMonth, st.wDay,
			  st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, data);

	DWORD dwReturnNum = 0;
	WriteFile(hFile, write_data, (DWORD)strlen(write_data), &dwReturnNum, NULL);

	// 关闭文件句柄
	CloseHandle(hFile);
}

//删除过期日志文件
void CLogWrite::DelLogFile(int days)
{
#if 0
	BOOL res;
	CTime ct;
	CString CurTime;
	CFileFind ff;
	CTimeSpan span = CTimeSpan(days,0,0,0);

	ct = CTime::GetCurrentTime();
	ct += span;

	CurTime.Format("%d-%02d-%02d",ct.GetYear(),ct.GetMonth(),ct.GetDay());

	CString path_str = FetchCurPath();
	path_str += "\\";
	path_str += g_log_file_name_prefix;
	path_str += "\\*.*";

	//if(!ff.FindFile(path_str))	//判断文件夹是否存在，不存在就创建文件夹
	//	CreateDirectory(path_str,NULL);

	res = ff.FindFile(path_str);
	while(res)
	{
		res = ff.FindNextFile();
		if(res == TRUE)
		{
			CString filepath,filename;

			if(ff.IsDirectory())
				continue;

			filename = ff.GetFileName();

			if(filename < CurTime)
			{
				filepath = FetchCurPath() + "\\" +g_log_file_name_prefix + "\\" + filename;
				DeleteFile(filepath);
			}
		}
	}
#endif
}
